﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Plugin1
{
    public class HttpClient
    {
        private string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        private byte[] form_data;
        private byte[] foot_data;

        public string FileName { get; set; }
        public string ConcentType { get; set; }

        public object Tag
        {
            get;
            set;
        }
        private HttpWebRequest webRequest = null;
        //public delegate void ResponseEventHandler(DocumentNodeModel responseResult);
        //public event ResponseEventHandler onResponseEventHandler;
        public delegate void RequestEventHandler();
        public event RequestEventHandler onRequestEventHandler;
        public Stream PostData { get; set; }
        Uri ClientUri;

        public HttpClient(Uri clientUri)
        {
            this.ClientUri = clientUri;
        }

        public void Post()
        {
            Uri endpoint = ClientUri;
            webRequest = WebRequest.Create(endpoint) as HttpWebRequest;
            webRequest.AllowReadStreamBuffering = false;
            //webRequest.AllowWriteStreamBuffering = false;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            webRequest.Method = "POST";

            //组织表单数据
            StringBuilder sb = new StringBuilder();

            sb.Append("--" + boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"image0\"; filename=\""+ FileName +"\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: " + ConcentType);
            sb.Append("\r\n\r\n");


            string head = sb.ToString();
            form_data = Encoding.UTF8.GetBytes(head);
            //结尾
            foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            //post总长度
            long length = form_data.Length + PostData.Length + foot_data.Length;
            webRequest.ContentLength = length;
            webRequest.BeginGetRequestStream(new AsyncCallback(RequestReady), webRequest);
        }

        private void RequestReady(IAsyncResult asyncResult)
        {
            if (this.onRequestEventHandler != null)
            {
                this.onRequestEventHandler();
            }
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
            Stream requestStream = request.EndGetRequestStream(asyncResult);

            requestStream.Write(form_data, 0, form_data.Length);
            //文件内容
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)PostData.Length))];
            int bytesRead = 0;
            while ((bytesRead = PostData.Read(buffer, 0, buffer.Length)) != 0)
                requestStream.Write(buffer, 0, bytesRead);
            requestStream.Write(foot_data, 0, foot_data.Length);
            requestStream.Close();

            PostData.Dispose();
            PostData.Close();
            webRequest.BeginGetResponse(new AsyncCallback(ResponseReady), webRequest);
        }

        private void ResponseReady(IAsyncResult asyncResult)
        {

            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
            WebResponse response = request.EndGetResponse(asyncResult);
            using (Stream responseStream = response.GetResponseStream())
            {
                String responseResult = String.Empty;
                try
                {
                    StreamReader reader = new StreamReader(responseStream);
                    responseResult = reader.ReadToEnd();

                }
                catch (WebException er)
                {
                }
                catch (Exception er)
                {
                }


            }
        }
    }
}
